package br.com.pascom.daoImpl;

import java.io.Serializable;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import util.HibernateUtil;
import br.com.pascom.dao.DAOGenerica;

public abstract class DAOImpl<T, I extends Serializable> implements DAOGenerica<T, I>{


	@Override
	public void save(T entity) {
		Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        session.save(entity);
        t.commit();
	}

	@Override
	public Object getById(Class classe, I id) {  
	    Object objeto = new Object();  
	    Session session = HibernateUtil.getSessionFactory().openSession();
	    try {  
	    	objeto = session.get(classe, id);  
	    } catch (Exception e) {  
	    	objeto = null;  
	    	e.printStackTrace();
	        throw e;  
	    } finally {  
	        session.close();  
	    }  
	    return objeto;  
	}

	@Override
	public List<T> list(Class<T> classe) {
		Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        List lista = session.createQuery("from " + classe.getSimpleName()).list();
        t.commit();
        return lista;
	}

	@Override
	public void remove(T entity) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction t = session.beginTransaction();
		session.delete(entity);
		t.commit();
	}

	@Override
	public void update(T entity) {
		Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        session.update(entity);
        t.commit();
	}
}
